# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
from ..base_parser import BasePageParser


class NewsListParser(BasePageParser):
    """新闻列表页解析器"""
    
    def can_handle(self, response):
        """判断是否为新闻列表页"""
        # 只处理列表页，不处理详情页
        if response.meta.get('page_type') == 'news_detail':
            return False
        return any(page_type in response.url for page_type in ['services-and-facilities'])
    
    def parse(self, response):
        next_page_type = 'news_detail'

        self.logger.info(f"正在解析列表页: {response.url}")
        
        soup = BeautifulSoup(response.text, 'html.parser')
        rows = soup.select(".wrapper > .grid > div")
        
        for row in rows:
            # 在每个row中查找a.boxin
            link = row.select_one('a')
            if link and link.get('href'):
                detail_url = self.urljoin(response.url, link['href'])

                if 'about' not in detail_url:
                    continue
                
                yield self.make_request(
                    detail_url,
                    callback=self.spider.parse,  # 返回主spider进行路由
                    meta={
                        'category_url': response.url,
                        'page_type': next_page_type,
                    }
                )
        